<?php
	require('common.php');
    
    // error check
    if(!isset($_POST['pw']))
        throw new Exception('Bad request.');
    if($_POST['pw'] != config('ROOT_PASSWORD')) {
        message(lang('BAD_PASSWORD'), 
                'install.php', 
                lang('BACK_TO_INSTALL'));
        exit();
    }
    
    // Create database
    $db = new Database();
    $db->query('CREATE TABLE '.config('DB_PREFIX').'users ('.
        'id INTEGER NOT NULL AUTO_INCREMENT, '.
        'name TEXT NOT NULL, '.
        'salt TEXT NOT NULL, '.
        'password TEXT NOT NULL, '.
        'group_id INTEGER NOT NULL, '.
        'real_name TEXT NOT NULL, '.
        'PRIMARY KEY (id))');
    $db->query('CREATE TABLE '.config('DB_PREFIX').'misc ('.
        'id INTEGER NOT NULL AUTO_INCREMENT, '.
        'name TEXT NOT NULL, '.
        'value TEXT NOT NULL, '.
        'PRIMARY KEY (id))');
    $db->query('CREATE TABLE '.config('DB_PREFIX').'blocks ('.
        'id INTEGER NOT NULL AUTO_INCREMENT, '.
        'name TEXT NOT NULL, '.
        'created INTEGER NOT NULL, '.
        'PRIMARY KEY (id))');
    $db->query('CREATE TABLE '.config('DB_PREFIX').'questions ('.
        'id INTEGER NOT NULL AUTO_INCREMENT, '.
        'question TEXT NOT NULL, '.
        'answer TEXT NOT NULL, '.
        'block INTEGER NOT NULL, '.
        'PRIMARY KEY (id))');
    $db->query('CREATE TABLE '.config('DB_PREFIX').'answers ('.
        'id INTEGER NOT NULL AUTO_INCREMENT, '.
        'user INTEGER NOT NULL, '.
        'question INTEGER NOT NULL, '.
        'answer TEXT NOT NULL, '.
        'correct BOOL NOT NULL, '.
        'time INTEGER NOT NULL, '.
        'PRIMARY KEY (id))');

    
    // Insert some basic data
    $salt = generateSalt();
    $db->query('INSERT INTO '.config('DB_PREFIX').'users '.
        '(name, salt, password, group_id, real_name) VALUES ('.
        '\'root\', '.
        '\''.$salt.'\', '.
        '\''.sha1($salt.config('ROOT_PASSWORD')).'\', 2, \'\')');
        
    // Success
    message(lang('INSTALL_SUCCESSFULL'), 
            'index.php', 
            lang('GOTO_HOME'));
?>